﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZSZ.DAL;
using ZSZ.IDAL;
using ZSZ.IService;
using ZSZ.Model;

namespace ZSZ.Service
{
    public partial class RolePermissionService : BaseService<RolePermission>, IRolePermissionService
    {
        /// <summary>
        /// 给角色roleId增加权限项id permIds
        /// </summary>
        /// <param name="roleId"></param>
        /// <param name="permIds"></param>
        public void Add(long roleId, long[] perpmissionIds)
        {
            //角色是否存在
            Role role = DbSession.RoleDal.GetById(roleId);
            if (role == null)
            {
                throw new ArgumentException("角色不存在" + roleId);
            }

            if (perpmissionIds == null)
            {
                throw new ArgumentException("未设置角色"+ roleId + "权限");
            }

            //权限是否存在
            var perms = DbSession.PermissionDal.GetAll().Where(p => perpmissionIds.Contains(p.Id)).ToArray();
            foreach (var perm in perms)
            {
                RolePermission rp = new RolePermission();
                rp.RoleId = role.Id;
                rp.PermissionId = perm.Id;
                rp.IsDeleted = false;
                rp.CreateDateTime = DateTime.Now;
                CurrentDal.Add(rp);
            }
            DbSession.SaveChanges();
        }

        public void Update(long roleId, long[] perpmissionIds)
        {
            //角色是否存在
            Role role = DbSession.RoleDal.GetById(roleId);
            if (role == null)
            {
                throw new ArgumentException("角色不存在" + roleId);
            }

            if (perpmissionIds == null)
            {
                throw new ArgumentException("未设置角色" + roleId + "权限");
            }

            //删除旧权限
            //role.RolePermissions.Clear();
            var rolePermissions = CurrentDal.GetAll().Where(rp => rp.RoleId== roleId);
            foreach (var rp in rolePermissions)
            {
                BatchDeleted(rp);
            }

            //权限是否存在
            var perms = DbSession.PermissionDal.GetAll().Where(p => perpmissionIds.Contains(p.Id)).ToArray();
            foreach (var perm in perms)
            {
                RolePermission rp = new RolePermission();
                rp.RoleId = role.Id;
                rp.PermissionId = perm.Id;
                rp.IsDeleted = false;
                rp.CreateDateTime = DateTime.Now;
                CurrentDal.Add(rp);
            }
            DbSession.SaveChanges();
        }
    }
}
